package win.smartown.mistyle.request;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable;

/**
 * Created by smartown on 2017/3/18.
 * <br>
 * Description:
 */
public class RequestManager {

    private static OkHttpClient okHttpClient;

    public static synchronized OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient.Builder()
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .addInterceptor(new Interceptor() {
                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            return chain.proceed(chain.request());
                        }
                    })
                    .build();
        }
        return okHttpClient;
    }

    private static Retrofit newRetrofit(String baseUrl) {
        return new Retrofit.Builder()
                .client(RequestManager.getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(baseUrl)
                .build();
    }

    public static class DoubanManager {

        private final static String baseUrl = "https://api.douban.com";
        private static Retrofit retrofit;

        private static synchronized Retrofit getRetrofit() {
            if (retrofit == null) {
                retrofit = RequestManager.newRetrofit(baseUrl);
            }
            return retrofit;
        }

        public static Observable<Object> search(String word) {
            return getRetrofit().create(DoubanService.class).search(word);
        }

    }

    public interface DoubanService {

        @GET("/v2/movie/search")
        Observable<Object> search(@Query("q") String word);

    }

}
